#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/6/6 上午10:16
# @Author  : Huang-Bo
import glob
import os
from datetime import datetime, timedelta
from utils.config_loader import load_config
from utils.logger import setup_logger

# -------------基础配置---------------
config = load_config()
success_logger = setup_logger("success", config["log"]["success_log"], level="INFO")
error_logger = setup_logger("error", config["log"]["error_log"], level="ERROR")


def clean_old_reports(report_dir='report', days_to_keep=7):
    """
    删除指定目录中早于days_to_keep 天前的报告文件
    """
    cutoff = datetime.now() - timedelta(days=days_to_keep)
    removed_count = 0
    for filepath in glob.glob(os.path.join(report_dir, '*.xlsx')):
        try:
            # 获取文件创建时间
            ctime = datetime.fromtimestamp(os.path.getmtime(filepath))
            if ctime < cutoff:
                os.remove(filepath)
                removed_count += 1
                success_logger.info(f"已删除旧报告文件: {filepath}")
        except Exception as e:
            error_logger.error(f"删除报告文件失败: {e}")
    success_logger.info(f"已删除 {removed_count} 个旧报告文件")
